package cn.hrc.controller.adm;

import cn.hrc.dao.FileMapper;
import cn.hrc.entity.Hot;
import cn.hrc.entity.LargeFile;
import cn.hrc.entity.XJson;
import cn.hrc.service.impl.FileServiceImpl;
import cn.hrc.service.impl.HotServiceImpl;
import cn.hrc.utils.PackJson;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;
import java.util.UUID;


@RestController
@RequestMapping("/api/adm/hot")
public class HotController {
    /** LoggerFactory.getLogger(this.getClass())  */
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    HotServiceImpl hotService;
    @Autowired
    RedisTemplate redisTemplate;
    @Autowired
    FileServiceImpl fileService;
    @RequestMapping("/findAll")
    public XJson findAll(){
        // 查询所有
        List<Hot> hots = hotService.findAll();
        return PackJson.pack(200,"ok",hots);
    }
    @GetMapping("/findById/{id}")
    public XJson findById(@PathVariable("id") int id){
        // 查询单个
        Hot hots = hotService.findById(id);
        return PackJson.pack(200,"ok",hots);
    }
    @RequestMapping("/addHot") //@RequestParam
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public XJson addHot(@RequestParam(value = "myPic",required = false) MultipartFile myFile,
                        Hot hot) {
        System.out.println("ADDHOT");
        String uuid = null;
        if (myFile != null && myFile.getSize() > 0){
            uuid = fileService.addFile(myFile);
        }
        hot.setPicture(uuid);
        // 添加
        hotService.addHot(hot);
        // 更新缓存
        return PackJson.pack(200,"ok",null);
    }
    @RequestMapping("/updHot")
    @Transactional(rollbackFor = Exception.class,propagation = Propagation.REQUIRED)
    public XJson updateHot(@RequestParam(value = "myPic",required = false) MultipartFile myFile,
                           Hot hot){
        String uuid = null;
        if (myFile != null && myFile.getSize() > 0){
            uuid = fileService.updFile(myFile,hot.getPicture());
        }
        hot.setPicture(uuid);
        // 更新
        hotService.updHot(hot);
        return PackJson.pack(200,"ok",null);
    }
    @GetMapping("/delHot/{id}")
    public XJson deleteHot(@PathVariable("id") int id){
        Hot hot = hotService.findById(id);
        // 删除图片
        fileService.delFile(hot.getPicture());
        // 删除
        hotService.deleteHot(id);
        //
        List<Hot> hots = hotService.findAll();
        return PackJson.pack(200,"ok",hots);
    }
}
